<template>
  <div>
    <!-- 顶部搜索栏 -->
    <div class="nav-search">
      <van-search
        v-model="queryInfo.keywords"
        placeholder="输入商户名、地点、找优惠"
        show-action
        shape="round"
        autofocus
        ref="searchRef"
        @input="onInput"
        @search="onSearch"
        @cancel="onCancel"
      />
    </div>
    <div class="container">
      <!-- 顶部榜单tab -->
      <van-tabs
        title-active-color="#fecb2f"
        swipeable
        color="#fecb2f"
        v-model="topNavValue"
        class="top-tab"
        v-if="isKeywordEmpty"
      >
        <van-tab>
          <div slot="title">
            <van-icon
              :name="topNavValue === 0 ? require('../assets/icon/search_qb_icon.png') : require('../assets/icon/search_qb1_icon.png')"
            />全部
          </div>
        </van-tab>
        <van-tab>
          <div slot="title">
            <van-icon
              :name="topNavValue === 1 ? require('../assets/icon/search_dp1_icon.png') : require('../assets/icon/search_dp_icon.png')"
            />点评
          </div>
        </van-tab>
        <van-tab>
          <div slot="title">
            <van-icon
              :name="topNavValue === 2 ? require('../assets/icon/search_dr1_icon.png') : require('../assets/icon/search_dr_icon.png')"
            />达人
          </div>
        </van-tab>
      </van-tabs>
      <!-- 无关键字面板 -->
      <div class="panel panel-recommend" v-if="isKeywordEmpty">
        <!-- 最近搜索 -->
        <van-row class="block" v-if="hasSearchHistory">
          <div class="flex-row-center">
            <h5>最近搜索</h5>
            <van-icon name="delete" @click="clearSearchHistoryList"></van-icon>
          </div>
          <van-tag
            round
            color="#eee"
            text-color="#333"
            size="large"
            v-for="(item, index) in searchHistoryList"
            :key="index"
            @click="search(item)"
          >{{item}}</van-tag>
        </van-row>
        <!-- 搜索发现 -->
        <van-row class="block">
          <div class="flex-row-center search-find">
            <h5>搜索发现</h5>
            <span @click="updateSearchFindList">换一换</span>
          </div>
          <van-tag
            round
            color="#eee"
            text-color="#333"
            size="large"
            v-for="(item, index) in searchFindList"
            :key="index"
            @click="search(item)"
          >{{item}}</van-tag>
        </van-row>
        <!-- 热搜榜 -->
        <van-row class="block">
          <!-- 标题部分 -->
          <div class="searchHot">
            <div class="searchHot-title">
              <van-icon name="location" color="#e15f08" />
              <span>成都热搜榜</span>
            </div>
            <div class="searchHot-range">
              <span>分钟即更新的各种权威榜单</span>
              <van-icon name="arrow" />
            </div>
          </div>
          <hr />
          <!-- 热搜列表 -->
          <van-grid :column-num="2" :border="false" :center="false">
            <van-grid-item
              v-for="(item, index) in searchHotList"
              :key="index"
              @click="search(item)"
            >
              <span class="hot-item">{{item}}</span>
            </van-grid-item>
          </van-grid>
        </van-row>
      </div>
      <!-- 有关键字面板 -->
      <div class="panel panel-result" v-else>
        <!-- 查询结果已返回 -->
        <div class="box-searchResult" v-if="hasSearchResult">
          <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
            <div
              class="item-result flex-row-center"
              v-for="item in searchResultList"
              :key="item.id"
              @click="onSearchListItemClick(item)"
            >
              <div class="item-result-left">
                <van-icon :name="item.icon"></van-icon>
              </div>
              <div class="item-result-middle">
                <div class="box-title" v-html="keywordConverter(item.name)"></div>
                <div class="box-evaluation" v-if="!item.count">
                  <van-rate
                    v-model="item.score"
                    size="10"
                    allow-half
                    readonly
                    void-icon="star"
                    void-color="#eee"
                  />
                </div>
                <div class="box-detail" v-if="!item.count">
                  <span>{{item.categoryName}}</span>|
                  <span>{{item.addressName}}</span>
                </div>
              </div>
              <div class="item-result-right">
                <span v-if="item.count">约{{item.count}}个结果</span>
                <span v-else>{{item.distance | distanceFilter}}</span>
              </div>
            </div>
          </van-list>
        </div>
        <!-- 查询结果尚未返回 -->
        <div class="box-emptyResult" @click="onSearch" v-else>
          <van-icon name="search"></van-icon>
          <span>
            查找“
            <i>{{queryInfo.keywords}}</i>”
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import _ from "lodash";

export default {
  name: "search",
  data() {
    return {
      searchFindList: [
        "春熙路",
        "太古里",
        "银泰中心in99",
        "小龙坎",
        "一点点",
        "冒椒火辣",
        "火锅",
        "串串"
      ],
      topNavValue: 0,
      searchHistoryList: [],
      searchHotList: ["儿童剪发", "班花麻辣烫", "兰蔻新春游园会", "牛扒"],
      searchResultList: [],
      // 是否正在上拉加载
      loading: false,
      finished: false,
      queryInfo: {
        keywords: "",
        categoryName: "",
        addressGPS: "",
        Highlight: "false",
        sortField: "score",
        sortRule: "ASC",
        page: 1
      },
      searchTimer: null
    };
  },
  created() {
    this.queryInfo.addressGPS = this.$store.state.position;
    this.queryInfo.keywords = this.$router.history.current.query.keyword;
    this.getSearchHistoryList();
    this.getSearchHotList();
  },
  mounted() {
    this.$refs.searchRef.querySelector("input").focus();
  },
  computed: {
    isKeywordEmpty() {
      return !this.queryInfo.keywords || this.queryInfo.keywords.length < 1;
    },
    hasSearchHistory() {
      return this.searchHistoryList.length > 0;
    },
    hasSearchResult() {
      return this.searchResultList.length > 0;
    }
  },
  methods: {
    // 下拉加载
    async getList() {
      const { data: res } = await this.$http.get("/api/search", this.queryInfo);
      this.loading = false;
      if (res.code !== 20000) {
        return this.$toast.fail("数据获取失败");
      }
      if (res.data.rows.length < 0) {
        this.finished = true;
      }
      this.searchResultList = [...this.searchResultList, ...res.data.rows];
    },
    // 关键词输入
    onInput() {
      this.searchResultList = [];
      if (!this.searchTimer) {
        this.searchTimer = setTimeout(async () => {
          this.searchTimer = null;
          this.queryInfo.page = 1;
          const { data: res } = await this.$http.get("/api/search");
          if (res.code !== 20000) {
            return this.$toast.fail("获取列表数据失败");
          }
          this.searchResultList = res.data.rows;
        }, 1000);
      }
    },
    // 输入框搜索事件
    onSearch() {
      this.search(this.queryInfo.keywords);
    },
    // 跳转到店铺列表页
    async search(keyword) {
      // 添加搜索历史
      await this.$http.post("/api/history/addHistory", {
        productName: this.queryInfo.keywords
      });
      // 查询关键词结果列表
      const { data: res } = await this.$http.get("/api/search", {
        params: this.queryInfo
      });
      console.log(res);
      // 跳转搜索结果列表页面
      this.$router.push({
        path: "/store/list",
        query: {
          keyword: this.queryInfo.keywords
        }
      });
    },
    onSearchListItemClick(item) {
      if (item.count) {
        this.search(item.name);
      } else {
        // 跳转店铺详情页面
        this.$router.push({
          path: "/store/detail",
          query: {
            storeId: item.id
          }
        });
      }
    },
    // 取消时返回前页
    onCancel() {
      this.$router.go(-1);
    },
    // 获取搜索历史
    async getSearchHistoryList() {
      const { data: res } = await this.$http.get("/api/history/findHistory");
      if (res.code !== 20000) {
        return this.$toast.fail("获取搜索历史失败");
      }
      this.searchHistoryList = res.data;
    },
    // 更新搜索发现列表
    updateSearchFindList() {
      this.searchFindList = _.shuffle(this.searchFindList);
    },
    // 高亮语法转换
    keywordConverter(title) {
      return title.replace(
        this.queryInfo.keywords,
        `<span class="title-keyword">${this.queryInfo.keywords}</span>`
      );
    },
    // 上拉加载事件
    onLoad() {
      if (!this.finished) {
        this.queryInfo.page++;
        this.getList();
      }
    },
    // 获取猜你喜欢
    async getSearchHotList() {
      const { data: res } = await this.$http.get(
        "/api/smartSearch/smartSearch",
        {
          params: {
            keyword: this.queryInfo.keywords
          }
        }
      );
      if (res.code !== 20000) {
        return this.$toast.fail("获取热搜数据失败");
      }
      this.searchHotList = res.data;
    }
  }
};
</script>
<style lang="less" scoped>
.nav-search {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}
hr {
  border: none;
  background-color: #ccc;
  height: 1px;
}
.panel {
  padding: 0 1em;
}

.container {
  margin-top: 54px;
}
.block {
  margin-top: 15px;
}
.block h5 {
  font-size: 0.8em;
  font-weight: 400;
  color: #666;
  line-height: 1.5em;
  margin: 0 0 10px;
}

.search-find span {
  color: #e15f08;
  font-size: 14px;
}
.searchHot {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.searchHot-title {
  display: flex;
  justify-content: flex-start;
  align-items: center;
}

.searchHot-range {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.searchHot-range span {
  font-size: 14px;
  color: #666;
}

.box-emptyResult {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  span {
    margin-left: 5px;
    i {
      font-style: normal;
      color: #e15f08;
    }
  }
}

.hot-item {
  font-size: 14px;
}

.item-result {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px 16px 16px 0;
  border-bottom: 1px solid #ccc;
  color: #999;
}

.item-result-middle {
  padding: 0 8px;
  flex-grow: 1;
  text-align: left;
  .box-title {
    font-weight: 700;
    color: #333;
  }
  .box-detail {
    font-size: 14px;
  }
}

// 选中后的样式(要放在全局样式里面)
.van-tab--active {
  color: #fcd848 !important;
  font-size: 18px !important;
  font-weight: 700 !important;
}
.van-tabs__line {
  background-color: #fcd848 !important;
}
.van-image .van-image__img {
  width: 40px !important;
}
</style>
